#include <cstdio>
#include <queue>

using namespace std;
bool mark[50][50][50];
int maze[50][50][50];

struct Node {
    int x, y, z;
    int t;
};

queue<Node> node_queue;

int next_step[][3] = {
        1, 0, 0,
        -1, 0, 0,
        0, 1, 0,
        0, -1, 0,
        0, 0, 1,
        0, 0, -1
};

//return the minimum time
int BFS(int a, int b, int c);


int main(int argc, char const *argv[]) {
    int times;
    scanf("%d", &times);
    for (int m = 0; m < times; m++) {
        int a, b, c, t;
        scanf("%d%d%d%d", &a, &b, &c, &t);
        for (int i = 0; i < a; i++) {
            for (int j = 0; j < b; j++) {
                for (int k = 0; k < c; k++) {
                    scanf("%d", &maze[i][j][k]);
                    mark[i][j][k] = false;
                }
            }
        }
        while (!node_queue.empty()) // clear
            node_queue.pop();
        //start node
        mark[0][0][0] = true;
        Node start_node;
        start_node.x = start_node.y = start_node.z = start_node.t = 0;
        node_queue.push(start_node);
        int result = BFS(a, b, c);
        if (result <= t)
            printf("%d\n", result);
        else
            printf("-1\n");
    }
    return 0;
}

int BFS(int a, int b, int c) {
    while (!node_queue.empty()) {
        Node current_node = node_queue.front();
        node_queue.pop();
        for (int i = 0; i < 6; ++i) {
            int next_x = current_node.x + next_step[i][0];
            int next_y = current_node.y + next_step[i][1];
            int next_z = current_node.z + next_step[i][2];
            if (next_x < 0 || next_x >= a || next_y < 0 || next_y >= b || next_z < 0 || next_z >= c)
                continue;
            if (maze[next_x][next_y][next_z] == 1) //wall
                continue;
            if (mark[next_x][next_y][next_z]) //have arrived
                continue;
            Node new_node;
            new_node.x = next_x;
            new_node.y = next_y;
            new_node.z = next_z;
            new_node.t = current_node.t + 1;
            node_queue.push(new_node);
            mark[next_x][next_y][next_z] = true;
            if (next_x == a - 1 && next_y == b - 1 && next_z == c - 1)
                return new_node.t;
        }
    }
    return -1;
}